import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import store from '@/store'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/home',
      component: () => import('@/views/sandbox/index.vue'),
      children: [
        {
          path: '/home',
          component: () => import('@/views/page/home.vue')
        },
        {
          path: '/songList',
          component: () => import('@/views/page/songList.vue')
        },
        {
          path: '/songer',
          component: () => import('@/views/page/songer.vue')
        },
        {
          path: '/search',
          component: () => import('@/views/page/search.vue')
        },
        {
          name: 'user',
          path: '/user',
          meta: {
            hiddenPlayer: true
          },
          component: () => import('@/views/page/user.vue')
        },
        {
          path: '/search',
          name: 'search',
          component: () => import('@/views/page/search.vue')
        }
      ]
    },
    {
      path: '/detail',
      component: () => import('@/views/page/detail.vue')
    },
    {
      name: 'login',
      path: '/login',
      meta: {
        hiddenPlayer: true
      },
      component: () => import('@/views/login/login.vue')
    },
    {
      path: '/:pathMatch*',
      name: 'notFound',
      meta: {
        hiddenPlayer: true
      },
      component: () => import('@/views/page/404.vue')
    },
    {
      path: '/401',
      name: '401',
      meta: {
        hiddenPlayer: true
      },
      component: () => import('@/views/page/401.vue')
    }
  ]
})

router.beforeEach((to, from, next) => {
  console.log(to);
  NProgress.start()
  if (to.matched.length === 0) {
    next({
      name: 'notFound'
    })
  } else if (to.path === '/user' && !store.state.userInfor.userNo) {
    return router.replace({ name: '401' })
  } else {
    next()
  }
})
router.afterEach(() => {
  NProgress.done()
})

export default router
